using System.ComponentModel;

namespace Silverlight.EntityFramework
{
    public sealed class Entity<EntityType, ValueType> : Entity<EntityType>, IEntity<ValueType>, IEntityNotifyPropertyChanged
        where EntityType : Entity<EntityType>
    {
        private IEntityValue<ValueType> _obj;

        private EntityType _entity;

        public Entity(string name, EntityType entity)
        {
            _obj = new EntityValue<ValueType>(name);
            _entity = entity;
        }

        public Entity(IEntityValue<EntityType, ValueType> obj)
        {
            _obj = obj;
            _entity = obj.Entity;
        }

        public static Entity<EntityType, ValueType> Create(IEntityValue<EntityType, ValueType> obj)
        {
            return new Entity<EntityType, ValueType>(obj);
        }

        public static Entity<EntityType, ValueType> Create(string entityName, EntityType owner)
        {
            return new Entity<EntityType, ValueType>(entityName, owner);
        }

        public ValueType Object
        {
            get { return _obj.Value; }
            set
            {
                if (!object.Equals(value, _obj.Value))
                {
                    _obj.Value = value;
                    if (_entity != null)
                    {
                        _entity.NotifyPropertyChanged(_obj.Name);
                    }
                }
            }
        }
    }

    public class Entity<EntityType> : IEntityNotifyPropertyChanged, IEditableObject
        where EntityType : Entity<EntityType>
    {
        #region INotyfyPropertyChange

        public event PropertyChangedEventHandler PropertyChanged;
        
        #endregion

        public void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #region IEditableObject Members

        public virtual void BeginEdit()
        {
        }

        public virtual void CancelEdit()
        {
        }

        public virtual void EndEdit()
        {
        }

        #endregion
    }
}
